package com.zgy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zgy.service.UserService;
import com.zgy.util.Page;
import com.zgy.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.zgy.pojo.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("demo/user")
public class UserController {
    @Autowired
    UserService service;

    @RequestMapping("queryPage")
    @ResponseBody
    public String queryPage(User user, @RequestParam("abc")Integer pageNo){
        int count = service.countUser(user);
        Page page= PageUtils.getPage(3,count,pageNo);
        List<User> list = service.queryPage(page,user);
        page.setData(list);
        return JSONObject.toJSONString(page);
    }
    @RequestMapping("/delUser")
    @ResponseBody
    public int delUser(@RequestParam("id") Integer id){
        service.delUser(id);
        return 1;
    }


    @RequestMapping("delDept")
    public String delDept(Dept dept){
        service.delDept(dept);
        return "redirect:/demo/dept_index.html";
    }
    @RequestMapping("queryDept")
    @ResponseBody
    public String queryDept(Dept dept){
        List<Dept> list = service.queryDept(dept);
        return JSONArray.toJSONString(list);
    }


    @RequestMapping("query")
    @ResponseBody
    public String query(User user){
        List<User> list = service.query(user);
        return JSONArray.toJSONString(list);
    }


    @RequestMapping("one")
    @ResponseBody
    public String one(User user){
        User us = service.one(user);
        List<Dept> list = service.dept();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user",us);
        jsonObject.put("list",list);
        return JSONObject.toJSONString(jsonObject);
    }


   /*
    @RequestMapping("dept")
    @ResponseBody
    public String dept(){
        List<Dept> list = service.dept();
        return JSONArray.toJSONString(list);
    }*/

    @RequestMapping("add")
    @ResponseBody
    public String add(User user){
        //判断：user 是否有id
        if(user.getId() != null && !user.getId().equals("")){
             //修改
            service.update(user);
        }else{
            //添加
            service.add(user);
        }
        return "1";
    }
}
